<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片项 -->
    <el-card class="box-card">
      <!-- 搜索/添加用户 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="refresh"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="openAddDialog">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="请输入用户信息"
        :visible.sync="addUserShow"
        width="30%"
        @close="addDiologClosed"
      >
        <span>
          <el-form
            :model="addForm"
            label-width="80px"
            :rules="addRules"
            ref="addFormRef"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserShow = false">取 消</el-button>
          <el-button type="primary" @click="addUser">提交</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框 -->
      <el-dialog
        title="请输入用户信息"
        :visible.sync="editUserShow"
        width="30%"
        @close="editDiologClosed"
      >
        <span>
          <el-form
            :model="editForm"
            label-width="80px"
            :rules="editRules"
            ref="editFormRef"
          >
            <el-form-item label="用户名">
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserShow = false">取 消</el-button>
          <el-button type="primary" @click="editUser">提交</el-button>
        </span>
      </el-dialog>

      <!-- 用户列表 -->
      <el-table :data="userlist" border style="width: 100%">
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="username" label="用户名" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="create_time" label="注册时间"> </el-table-column>
        <el-table-column prop="mg_state" label="用户状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="updateStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              circle
              @click="openEditDialog(scope.row.id)"
            ></el-button>

            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              circle
              @click="deleteUser(scope.row.id)"
            ></el-button>

            <el-tooltip
              class="item"
              effect="dark"
              content="角色设置"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-star-off"
                size="mini"
                circle
                @click="rolerSetting(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 角色设置对话框 -->
    <el-dialog title="角色设置" :visible.sync="rolerDialogVisible" width="30%">
      <p>当前用户名：{{ userInfo.username }}</p>
      <p>当前角色名：{{ userInfo.role_name }}</p>
      <p>
        设置角色
        <el-select v-model="selectedID" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleAction"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data: function () {
    //自定义邮箱校验规则对象
    var checkEmail = (rule, value, callback) => {
      //验证邮箱正则表达式
      const emailReg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
      if (emailReg.test(value)) {
        return callback();
      }
      return callback(new Error("邮箱格式有误"));
    };
    //自定义手机号校验规则对象
    var checkMobile = (rule, value, callback) => {
      //验证邮箱正则表达式
      const mobileReg = /^1[34578]\d{9}$/;
      if (mobileReg.test(value)) {
        return callback();
      }
      return callback(new Error("手机号格式有误"));
    };
    return {
      //用户列表查询条件
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      total: 0,
      //查询到的用户列表
      userlist: [],
      //添加用户对话框显示/隐藏 标志位
      addUserShow: false,
      //修改用户对话框显示/隐藏 标志位
      editUserShow: false,
      //新增用户表单对象
      addForm: {
        username: "",
        mobile: "",
        password: "",
        email: "",
      },

      //新增用户信息验证规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
      },
      //修改用户表单数据
      editForm: {
        id: "",
        username: "",
        email: "",
        mobile: "",
      },
      //修改用户表单验证规则
      editRules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
      },
      //角色设置对话框标志位
      rolerDialogVisible: false,
      //记录当前角色设置对话框对应的角色
      userInfo: {},
      //角色列表
      roleList: [],
      //已选中的角色ID
      selectedID: ''
    };
  },
  created: function () {
    this.getUserList();
  },
  methods: {
    //发送请求，获取用户列表
    getUserList: async function () {
      const { data: res } = await this.$http.get("/users", {
        params: this.queryInfo,
      });
      if (res.meta.status != 200) {
        return this.$message.error("获取用户列表失败");
      }
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    //监听页面容量发送变化事件
    handleSizeChange: function (nowSize) {
      this.queryInfo.pagesize = nowSize;
      this.getUserList();
    },
    //监听页码发生变化事件
    handleCurrentChange: function (nowPage) {
      this.queryInfo.pagenum = nowPage;
      this.getUserList();
    },
    //监听switch开关状态 更新用户状态
    updateStatus: async function (row) {
      const { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      );
      if (res.meta.status != 200) {
        row.mg_state = !row.mg_state;
        return this.$message.error("状态更新失败！");
      }
      this.$message.success("状态更新成功！");
    },
    //搜索用户功能
    search: function () {
      this.getUserList();
    },
    //情况搜索域后刷新搜索结果
    refresh: function () {
      this.queryInfo.query = "";
      this.getUserList();
    },
    //添加用户对话框
    openAddDialog: function () {
      this.addUserShow = true;
    },
    //监听添加用户对话框关闭事件
    addDiologClosed: function () {
      this.$refs.addFormRef.resetFields();
    },
    //添加用户
    addUser: function () {
      //验证用户输入是否合法
      this.$refs.addFormRef.validate(async (result) => {
        if (!result) return;
        //如果合法则发送请求，添加用户
        const { data } = await this.$http.post("/users", this.addForm);
        if (data.meta.status != 201) return this.$message.error("用户添加失败");
        //添加成功
        this.$message.success("用户添加成功！");
        //关闭添加页
        this.addUserShow = false;
        //刷新用户列表
        this.getUserList();
      });
    },
    //监听修改用户信息按钮点击事件
    openEditDialog: async function (id) {
      //打开修改用户对话框
      this.editUserShow = true;
      //发送请求获取用户数据
      const { data: res } = await this.$http.get("/users/" + id);
      //给输入框赋值
      this.editForm.id = res.data.id;
      this.editForm.username = res.data.username;
      this.editForm.mobile = res.data.mobile;
      this.editForm.email = res.data.email;
    },
    //监听修改用户对话框关闭事件
    editDiologClosed: function () {
      this.$refs.editFormRef.resetFields();
    },
    //修改用户
    editUser: function () {
      this.$refs.editFormRef.validate(async (result) => {
        if (!result) return;
        //发送请求，修改用户信息
        const { data } = await this.$http.put("/users/" + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        });
        if (data.meta.status != 200) return this.$message.error("修改失败");
        this.editUserShow = false;
        //修改成功
        this.$message.success("用户修改成功！");
        //刷新用户列表
        this.getUserList();
      });
    },
    //删除用户
    deleteUser: async function (id) {
      const confirmRes = await this.$confirm("是否永久删除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((error) => error);
      if (confirmRes != "confirm") return this.$message.info("已取消删除");
      const { data: res } = await this.$http.delete("/users/" + id);
      if (res.meta.status != 200) return this.$message.error("删除失败");
      //删除成功
      this.$message.success("删除成功！");
      //刷新用户列表
      this.getUserList();
    },
    //设置用户角色
    rolerSetting: async function (user) {
      //打开用户角色设置对话框
      this.rolerDialogVisible = true;
      //将当前行对应用户信息展示在页面上
      this.userInfo = user;
      //查询出所有的角色
      const { data: res } = await this.$http.get("/roles");
      if (res.meta.status != 200)
        return this.$message.error("角色列表查询失败！");
      this.roleList = res.data;
    },
    //发送请求，设置用户角色
    setRoleAction: async function(){
      const {data: res} = await this.$http.put(`/users/${this.userInfo.id}/role`,{
        rid: this.selectedID
      })
      if(res.meta.status != 200) return this.$message.error('角色设置失败')
      this.$message.success('角色设置成功')
      //关闭角色设置对话框
      this.rolerDialogVisible = false;
      //清空选中的角色ID
      this.selectedID  = '';
      //刷新用户列表
      this.getUserList()
    }
  },
};
</script>